<!-- 店铺统计 -->
<template>
  <div class="gl_contentBox gl_heightFull" style="padding: 0">
    <div v-loading="loading" class="gl_padding_15" style="margin-bottom: 50px">
      <div class="gl_searchBox gl_mt_5 gl_mb_15">
        <el-row :gutter="20">
          <el-col :span="8" :lg="6">
            <p>统计时间</p>
            <el-date-picker
              v-model="filterDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%;"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              size="mini"
              :clearable="false"
              @change="handleTimeChange"
            />
          </el-col>
          <el-col :span="16" :lg="18" align="right">
            <el-button style="margin-top: 27px" type="primary" size="mini" @click="getData()">查询</el-button>
            <el-button style="margin-top: 27px" type="warning" size="mini" @click="initForm()">重置</el-button>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="15">
        <template v-for="(item, index) in detailsList">
          <el-col v-if="index < 2" :key="index" :span="6">
            <div class="box" :style="{ backgroundImage: 'url(' + item.bgImg + ')' }">
              <p class="gl_mb_5 gl_fs_14">{{ item.name }}</p>
              <p :style="{ color: item.color }">{{ item.sum }}</p>
            </div>
          </el-col>
        </template>
      </el-row>
      <el-divider />
      <el-row :gutter="15">
        <template v-for="(item, index) in detailsList">
          <el-col v-if="index > 1" :key="index" :span="6">
            <div class="box" :style="{ backgroundImage: 'url(' + item.bgImg + ')' }">
              <p class="gl_mb_5 gl_fs_14">{{ item.name }}</p>
              <p :style="{ color: item.color }">{{ item.sum }}</p>
            </div>
          </el-col>
        </template>
      </el-row>
      <div style="margin-left: 35px; margin-top: 62px;">
        <p style="margin-left: 48px" class="gl_fs_16 gl_ft_weight">商城订单/销售额</p>
        <el-divider />
        <div v-loading="barLoading" class="details_box">
          <div>
            <BarChart :default-data="orderData" :width="barWidth" :height="barHeight" />
          </div>
          <div v-if="orderData.series[0].data.length < 1" class="no_echart">暂无数据</div>
        </div>
        <div v-loading="lineLoading" class="details_box" style="margin-top: 70px">
          <div>
            <LineChart :default-data="salesVolume" :width="barWidth" :height="barHeight" />
          </div>
          <div v-if="salesVolume.series[0].data.length < 1" class="no_echart">暂无数据</div>
        </div>
      </div>
    </div>
    <OrderDialog ref="orderDialog" />
    <FinishDialog ref="finishDialog" />
  </div>
</template>

<script>
import OrderDialog from './components/orderDialog';
import FinishDialog from './components/finishDialog';
import LineChart from './components/LineChart';
import BarChart from './components/BarChart';
import { api_GET_ClubBranchMallStatistic, api_GET_ClubBranchMallOrderCountByDayOrgnazitionUnitId, api_GET_ClubBranchMallOrderAmountByDayOrgnazitionUnitId } from '@/extend/api/hallswaggerApi/app.js';
import { Api_GET_ClubBranchMallStatisticQO } from '@/lib/form/hall/swaggerForm';
export default {
  components: {
    OrderDialog,
    FinishDialog,
    LineChart,
    BarChart
  },
  data () {
    return {
      loading: false,
      barLoading: false,
      lineLoading: false,
      barWidth: '100%',
      barHeight: '342px',
      branchId: '', // 道馆id
      filterDate: [], // 统计时间
      form: new Api_GET_ClubBranchMallStatisticQO(),
      detailsList: [
        {
          code: 'totalOrder',
          name: '已完成订单总数（个）',
          sum: 0,
          color: '#c10000',
          bgImg: require('@/assets/images/mall/statistics_bg_1.png'),
          routeName: '',
          key: 'finishDialog',
          dialogTitle: '已完成订单'
        },
        {
          code: 'soldAmount',
          name: '已售总额（元）',
          sum: 0.00,
          color: '#cd7d00',
          bgImg: require('@/assets/images/mall/statistics_bg_2.png'),
          routeName: '',
          key: 'finishDialog',
          dialogTitle: '已售总额'
        },
        {
          code: 'sell',
          name: '销售中的商品（个）',
          sum: 0,
          color: '#71bd00',
          bgImg: require('@/assets/images/mall/statistics_bg_3.png'),
          routeName: 'goodsType',
          query: 'onShelf'
        },
        {
          code: 'goods',
          name: '仓库中的商品（个）',
          sum: 0,
          color: '#06b5b5',
          bgImg: require('@/assets/images/mall/statistics_bg_4.png'),
          routeName: 'goodsType',
          query: 'inStorage'
        },
        {
          code: 'unPaidOrder',
          name: '待付款订单（个）',
          sum: 0,
          color: '#21009c',
          bgImg: require('@/assets/images/mall/statistics_bg_5.png'),
          routeName: '',
          key: 'orderDialog',
          dialogTitle: '待付款订单'
        },
        {
          code: 'notShippedOrder',
          name: '待发货订单（个）',
          sum: 0,
          color: '#0085a8',
          bgImg: require('@/assets/images/mall/statistics_bg_6.png'),
          routeName: '',
          key: 'orderDialog',
          dialogTitle: '待发货订单'
        }
      ],
      orderData: { // 订单
        title: {
          text: '近十天订单数（个）',
          textStyle: {
            color: '#333',
            fontWeight: 'bold'
          }
        },
        tooltip: { // 提示框
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          backgroundColor: '#fff',
          textStyle: {
            color: '#595959'
          },
          extraCssText: 'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.15)',
          padding: [8, 16],
          borderRadius: 3
        },
        color: ['#1890ff'],
        grid: { // 绘图网格
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true // 是否包含刻度标签
        },
        xAxis: {
          type: 'category',
          boundaryGap: [0, 0.01],
          axisLine: { // 坐标轴线
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          axisTick: { // 坐标轴刻度
            alignWithLabel: true // 刻度与标签对齐
          },
          axisLabel: { // 刻度标签
            color: '#595959'
          },
          data: []
        },
        yAxis: {
          type: 'value',
          minInterval: 1, // 保证坐标轴分割刻度显示成整数
          axisLine: { // 坐标轴线
            show: false,
            lineStyle: {
              color: '#595959'
            }
          },
          axisTick: { // 坐标轴刻度
            show: false
          },
          splitLine: { // grid分隔线
            show: true,
            lineStyle: {
              type: 'dashed',
              color: ['#E8E8E8']
            }
          },
          splitArea: { // grid分隔区域
            show: false
          }
        },
        series: [
          {
            name: '订单数',
            type: 'bar',
            barWidth: 24,
            data: []
          }
        ]
      },
      salesVolume: { // 销售额
        title: {
          text: '近十天销售额（元）',
          textStyle: {
            color: '#333',
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          backgroundColor: '#fff',
          textStyle: {
            color: '#595959'
          },
          extraCssText: 'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.15)',
          padding: [8, 16],
          borderRadius: 3
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLine: { // 坐标轴线
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          axisTick: { // 坐标轴刻度
            alignWithLabel: true // 刻度与标签对齐
          },
          axisLabel: { // 刻度标签
            color: '#595959'
          }
        },
        yAxis: {
          axisLine: { // 坐标轴线
            show: false,
            lineStyle: {
              color: '#595959'
            }
          },
          axisTick: { // 坐标轴刻度
            show: false
          },
          splitLine: { // grid分隔线
            show: true,
            lineStyle: {
              type: 'dashed',
              color: ['#E8E8E8']
            }
          },
          splitArea: { // grid分隔区域
            show: false
          }
        },
        series: [
          {
            name: '销售额',
            type: 'line',
            smooth: false, // 折线是否平滑显示
            itemStyle: {
              normal: {
                color: '#2fc25b',
                lineStyle: {
                  color: '#2fc25b',
                  width: 2
                }
              }
            },
            data: [],
            animationDuration: 2800
          }
        ]
      }
    };
  },
  created() {
    this.getMallStoreCurrent();
  },
  methods: {
    // 获取当前用户店铺信息
    getMallStoreCurrent() {
      this.branchId = this.$route.query.branchid;
      this.initForm();
      this.getEChartsData();
    },
    // 获取数字信息
    getData() {
      var that = this;
      that.loading = true;
      that.form.OrgnazitionUnitId = that.branchId;
      api_GET_ClubBranchMallStatistic(that.form).then(res => {
        that.loading = false;
        that.detailsList[0].sum = res.finishedOrderCount;
        that.detailsList[1].sum = res.amount ? that.formatMoney(res.amount) : '0.00';
        that.detailsList[2].sum = res.onShelfProductCount;
        that.detailsList[3].sum = res.inStorageProductCount;
        that.detailsList[4].sum = res.unpaidOrderCount;
        that.detailsList[5].sum = res.unShippedOrderCount;
      }, (error) => {
        that.loading = false;
        that.$message({ type: 'error', message: '获取店铺统计失败！' + (error.error && error.error.message || '') });
      });
    },
    // 获取图表信息
    getEChartsData() {
      // 订单数
      var that = this;
      that.barLoading = true;
      api_GET_ClubBranchMallOrderCountByDayOrgnazitionUnitId(that.branchId).then(res => {
        that.barLoading = false;
        const orderCount = res || [];
        const count = that.handleEChartsData(orderCount, 'count');
        that.orderData.xAxis.data = count.xAxis;
        that.orderData.series[0].data = count.yAxis;
      }, (error) => {
        that.barLoading = false;
        that.$message({ type: 'error', message: '获取订单数图表失败！' + (error.error && error.error.message || '') });
      });
      // 销售额
      this.lineLoading = true;
      api_GET_ClubBranchMallOrderAmountByDayOrgnazitionUnitId(this.branchId).then(res => {
        this.lineLoading = false;
        const orderAmount = res || [];
        const amount = that.handleEChartsData(orderAmount, 'amount');
        that.salesVolume.xAxis.data = amount.xAxis;
        that.salesVolume.series[0].data = amount.yAxis;
      }, (error) => {
        this.lineLoading = false;
        this.$message({ type: 'error', message: '获取销售额图表失败！' + (error.error && error.error.message || '') });
      });
    },
    // 初始
    initForm() {
      const day1 = this.handleDate(-30, '-');
      const day2 = this.handleDate(0, '-');
      this.filterDate = [day1, day2];
      this.form.StartDate = day1;
      this.form.EndDate = day2;
      this.getData();
    },
    // 处理订单数
    handleEChartsData(data, code) {
      const obj = {
        xAxis: [],
        yAxis: []
      };
      for (var i = 0; i < data.length; i++) {
        var item = data[i];
        item.dateTime = item.dateTime.substring(5, 7) + '月' + item.dateTime.substring(8, 10) + '日';
        obj.xAxis.push(item.dateTime);
        if (code && code === 'count') {
          obj.yAxis.push(item.orderCount);
        } else {
          const amount = this.formatMoney(item.orderAmount);
          obj.yAxis.push(amount);
        }
      }
      return obj;
    },
    // 处理初始的统计时间
    handleDate (num, str) {
      var today = new Date();
      var nowTime = today.getTime();
      var ms = 24 * 3600 * 1000 * num;
      today.setTime(parseInt(nowTime + ms));
      var oYear = today.getFullYear();
      var oMoth = (today.getMonth() + 1).toString();
      if (oMoth.length <= 1) oMoth = '0' + oMoth;
      var oDay = today.getDate().toString();
      if (oDay.length <= 1) oDay = '0' + oDay;
      return oYear + str + oMoth + str + oDay;
    },
    // 处理时间筛选项
    handleTimeChange(time) {
      this.form.StartDate = time && time[0];
      this.form.EndDate = time && time[1];
      this.getData();
    },
    jumpRoute(item) {
      if (item.routeName) {
        const query = item.routeName === 'goodsType' && item.query ? { activeTab: item.query } : '';
        this.$router.push({
          name: item.routeName,
          query: query
        });
      } else {
        this.$refs[item.key].open(this.branchId, item.dialogTitle, this.form.StartDate, this.form.EndDate);
      }
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.box {
  // width: 260px;
  width: 100%;
  height: 114px;
  padding: 20px 26px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.09);
  color: #8C8A8A;
  font-size: 30px;
  display: inline-block;
  // margin-right: 20px;
  // cursor: pointer;
  transition: all .4s ease 0s;
}
// .box:last-child {
//   margin-right: 0px;
// }
// .box:hover {
//   transform: scale(1.1);
//   box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.09);
// }
.el-divider--horizontal {
  margin: 15px 0;
}
.details_box {
  margin-top: 24px;
  margin-left: 40px;
  position: relative;
}
.no_echart {
  width: 100%;
  height: 340px;
  line-height: 330px;
  text-align: center;
  color: #515a6e;
  font-size: 12px;
  position: absolute;
  top: 30px;
  z-index: 99;
  background: #fff;
}
</style>
